package com.jilian.mydemo.modul.user.activity;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.contrarywind.view.WheelView;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseEventMsg;
import com.jilian.mydemo.city.Interface.OnCityItemClickListener;
import com.jilian.mydemo.city.bean.CityBean;
import com.jilian.mydemo.city.bean.DistrictBean;
import com.jilian.mydemo.city.bean.ProvinceBean;
import com.jilian.mydemo.city.style.citypickerview.CityPickerView;
import com.jilian.mydemo.common.dto.MyInfoDto;
import com.jilian.mydemo.common.dto.MyInfoRefreshDto;
import com.jilian.mydemo.common.vo.ServiceAreaVo;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.event.RxBus;
import com.jilian.mydemo.factory.Factoty;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.order.adapter.ServiceWheelAdapter;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.modul.user.adapter.AreaAdapter;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.PermissionsObserver;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.UrlUtils;
import com.jilian.mydemo.utils.selectphoto.SelectPhotoUtils;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.jilian.mydemo.Constant.FINALVALUE.FILE_PROVIDER;

public class UpdateMyInfoActivity extends BaseActivity implements CustomItemClickListener {
    private LinearLayout llUpdateHead;
    private TextView tvNickNameText;
    private TextView tvNickName;
    private RecyclerView recyclerview;
    private TextView tvAdd;
    private TextView tvOk;
    private List<ServiceAreaVo> serviceDataList;
    private LinearLayoutManager linearLayoutManager;
    private AreaAdapter areaAdapter;
    private ImageView ivHead;
    private UserViewModel userViewModel;
    private OrderViewModel orderViewModel;
    private List<ServiceAreaVo> serviceList;
    private TextView tvSix;
    private EditText etHydraulicSkills;
    private TextView etAdress;
    private EditText etAdressDetail;
    private LinearLayout llAdress;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        userViewModel = Factoty.getViewModel(UserViewModel.class, UpdateMyInfoActivity.this);
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_updatemyinfo;
    }

    @Override
    public void initView() {
        setNormalTitle("修改个人信息", v -> finish());
        llAdress = (LinearLayout) findViewById(R.id.ll_adress);
        llUpdateHead = (LinearLayout) findViewById(R.id.ll_update_head);
        tvNickNameText = (TextView) findViewById(R.id.tv_nick_name_text);
        tvNickName = (TextView) findViewById(R.id.tv_nick_name);
        tvSix = (TextView) findViewById(R.id.tv_six);
        etHydraulicSkills = (EditText) findViewById(R.id.et_hydraulic_skills);
        etAdress = (TextView) findViewById(R.id.et_adress);
        etAdressDetail = (EditText) findViewById(R.id.et_adress_detail);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        tvAdd = (TextView) findViewById(R.id.tv_add);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        ivHead = (ImageView) findViewById(R.id.iv_head);
        //
        serviceList = new ArrayList<>();
        serviceDataList = new ArrayList<>();
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(linearLayoutManager);
        areaAdapter = new AreaAdapter(this, serviceList, this);
        recyclerview.setAdapter(areaAdapter);
    }


    private MyInfoDto mDto;

    @Override
    public void initData() {
        mDto = (MyInfoDto) getIntent().getSerializableExtra("mDto");
        if (mDto != null) {
            tvNickName.setText(mDto.getUserName());
            Glide
                    .with(UpdateMyInfoActivity.this)
                    .load(UrlUtils.getUrl(mDto.getUserImg()))
                    .error(R.drawable.iv_default_head)
                    .into(ivHead);
            List<ServiceAreaVo> list = mDto.getServiceAreas();
            if (EmptyUtils.isNotEmpty(list)) {
                serviceDataList.addAll(list);
                areaAdapter.notifyDataSetChanged();
            }
            tvSix.setText(mDto.getSex());
            etAdress.setText(mDto.getArea());
            etAdressDetail.setText(mDto.getContactAddress());
            etHydraulicSkills.setText(mDto.getSkill());
        }
    }

    /**
     * 处理选择的地址
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1001:
                    getLoadingDialog().dismiss();
                    CityPickerView pickerView = (CityPickerView) msg.obj;
                    pickerView.showCityPicker();
                    //监听选择点击事件及返回结果
                    pickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
                        @Override
                        public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                            etAdress.setText(province.getPROVINCE() + city.getCITY() + district.getAREA());
                        }

                        @Override
                        public void onCancel() {
                            ToastUitl.showImageToastTips("已取消");
                        }
                    });
                    break;
                case 1002:
                    getLoadingDialog().dismiss();
                    CityPickerView pickerView2 = (CityPickerView) msg.obj;
                    pickerView2.showCityPicker();
                    //监听选择点击事件及返回结果
                    pickerView2.setOnCityItemClickListener(new OnCityItemClickListener() {
                        @Override
                        public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                            ServiceAreaVo vo = new ServiceAreaVo();
                            vo.setProvince(province.getPROVINCE());
                            vo.setCity(city.getCITY());
                            vo.setDistrict(district.getAREA());
                            serviceList.add(vo);
                            areaAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onCancel() {
                            ToastUitl.showImageToastTips("已取消");
                        }
                    });
                    break;
            }
        }
    };

    @Override
    public void initListener() {
        /**
         * 选择联系地址
         */
        llAdress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLoadingDialog().showDialog();
                new Thread() {
                    @Override
                    public void run() {
                        CityPickerView pickerView = getPickerInstance("选择联系地址",2);
                        Message message = Message.obtain();
                        message.obj = pickerView;
                        message.what = 1001;
                        handler.sendMessage(message);
                    }
                }.start();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog();
                userViewModel.updateUserInfo(serviceList,etAdress.getText().toString(),etAdressDetail.getText().toString(),etHydraulicSkills.getText().toString(), files);
                userViewModel.getUpdateUserliveData().observe(UpdateMyInfoActivity.this, new Observer<BaseDto>() {
                    @Override
                    public void onChanged(@Nullable BaseDto dto) {
                        hideLoadingDialog();
                        if (dto.isSuccess()) {
                            ToastUitl.showImageToastSuccess(dto.getMsg());
                            //通知刷新UI
                            MyInfoRefreshDto refreshDto = new MyInfoRefreshDto();
                            refreshDto.setCode(100);
                            BaseEventMsg msg = new BaseEventMsg();
                            msg.setMyInfoRefreshDto(refreshDto);
                            RxBus.getInstance().post(msg);
                            finish();
                        } else {
                            ToastUitl.showImageToastTips(dto.getMsg());
                        }
                    }
                });
            }
        });
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取 后台配置的服务列表
               getAllOffice();
            }
        });
        llUpdateHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectPhotoTypeDialog();
            }
        });
    }

    /**
     * 获取后台配置的服务区域
     */
    private void getAllOffice() {
        showLoadingDialog();
        orderViewModel.queryAllOffice();
        orderViewModel.getServiceArealiveData().observe(UpdateMyInfoActivity.this, new Observer<BaseDto<List<ProvinceBean>>>() {
            @Override
            public void onChanged(@Nullable BaseDto<List<ProvinceBean>> listBaseDto) {
                hideLoadingDialog();
                if (listBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(listBaseDto.getData())) {
                        setJson(JSONObject.toJSONString(listBaseDto.getData()));
                        showServiceDialog();
                    } else {
                        ToastUitl.showImageToastTips("未获取到服务区域");
                        return;
                    }


                } else {
                    ToastUitl.showImageToastTips(listBaseDto.getMsg());
                }
            }
        });
    }

    /**
     * 选择服务区域对话框
     */
    private void showServiceDialog() {
        getLoadingDialog().showDialog();
        new Thread() {
            @Override
            public void run() {
                CityPickerView pickerView = getPickerInstance("选择服务区域",1);
                Message message = Message.obtain();
                message.obj = pickerView;
                message.what = 1002;
                handler.sendMessage(message);
            }
        }.start();
    }

    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;

    /**
     * 选中照片
     */
    private void showSelectPhotoTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_photo_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        Button btnTakingPictures = (Button) holder.getView(R.id.btn_taking_pictures);
                        Button btnPhotoAlbum = (Button) holder.getView(R.id.btn_photo_album);
                        Button btnCancel = (Button) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //拍照
                        btnTakingPictures.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                RxPermissions.getInstance(UpdateMyInfoActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromCapture(UpdateMyInfoActivity.this, FILE_PROVIDER, FROM_CAPTURE);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }
                        });
                        //相册
                        btnPhotoAlbum.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();

                                RxPermissions.getInstance(UpdateMyInfoActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromAlbum(UpdateMyInfoActivity.this, FILE_PROVIDER, 1, FROM_ALBUM);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }

                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    Uri uri = uriList.get(0);
                    initPath(SelectPhotoUtils.getRealPathFromURI(this, uri));
                    break;
                //相机
                case FROM_CAPTURE:
                    initPath(SelectPhotoUtils.capturePathResult());
                    break;
            }

        }
    }

    private List<File> files;

    /**
     * 展示选择的头像
     *
     * @param url
     */
    private void initPath(String url) {
        files = new ArrayList<>();
        files.add(new File(url));
        Glide
                .with(this)
                .load(url)
                .into(ivHead);
    }

    @Override
    public void onItemClick(View view, int position) {

    }


}
